import { Button, Form, Message, NumberPicker, Dialog } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useRef, useState, useEffect } from 'react';
import DrawerFooter from '@/components/DrawerFooter';
import { observable } from 'mobx';
import TauSimpleSelect from '@/components/TauSimpleSelect';
import { observer } from 'mobx-react-lite';
import { useStore } from '@/hooks';
import { FieldsGrid } from '../stores/definitions';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';
import SuperAddition from './SuperAddition';

const tableId = uniqueId('tauTable-');

const RelevancyActivity = ({ activity, modal, visible, onCancel, onSubmit, ...formProps }) => {
  const [formData] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current;
  const { activityStore: store } = useStore();
  const [selectValue, setSelectValue] = useState();
  const [superAddition, setSuperAddition] = useState();
  const [state, setState] = useState({
    haveApplied: [],
    notApplied: [],
  });

  const [currentPage, setCurrentPage] = useState({
    haveApplied: 0,
    notApplied: 0,
  }); // 默认页数

  const [pageSize, setPageSize] = useState({
    haveApplied: 10,
    notApplied: 10,
  }); // 每页显示的数据数量

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      await init();
    })();
    return (() => {
      _.set(formData, 'batchId', '');
      _.set(formData, 'requestedQuantity', '');
    });
  }, [visible]);

  async function init() {
    const info = await store.get(activity?.id);
    _.assign(formData, info);
    await store.getCoupons({ search: { enable: true } });
    const getApply = await store.getBatchApply({ activityId: activity?.id });
    const have = await store.getCouponAPPlies({ search: { activityIds: [activity.id] } });
    const toggle = have?.map((item) => {
      const { value } = item;
      const findBatch = getApply?.find((p) => p.batchId === value);
      if (findBatch) {
        const { requestedQuantity, distributionQuantity } = findBatch;
        item.mayApply = requestedQuantity - distributionQuantity;
      }
      return item;
    });
    const res = await fetchEnableBatches(toggle);
    const filterCoupon = store.coupons.filter((item) => !res.some(((p) => item.value === p.value)));
    store.coupons = filterCoupon;
    setState({ ...state, haveApplied: res });
  }

  async function fetchEnableBatches(arr) {
    const enableBatch = arr.map(async (item) => {
      return store.api.getBatchId(item?.value).then((res) => ({
        ...item,
        enable: res?.enable,
      }));
    });
    return await Promise.all(enableBatch);
  }

  // 根据当前页码和每页数量获取当前页需要显示的数据
  const haveStartIndex = currentPage.haveApplied * pageSize.haveApplied;
  const haveEndIndex = haveStartIndex + pageSize.haveApplied;
  const haveCurrentPageData = state.haveApplied.slice(haveStartIndex, haveEndIndex);

  const notStartIndex = currentPage.notApplied * pageSize.notApplied;
  const notEndIndex = notStartIndex + pageSize.notApplied;
  const notCurrentPageData = state.notApplied.slice(notStartIndex, notEndIndex);

  const overrideModel = {
    batchId: {
      ui: {
        renderer: () => (
          <div style={{ display: 'flex' }}>
            <TauSimpleSelect style={{ width: 300 }} onChange={(e, _, r) => handleSelectBatch(e, _, r)} data={store.coupons} />
            <Button style={{ marginLeft: 30 }} type="primary" onClick={() => handleAddBatch()}>{t`添加批次`}</Button>
          </div>),
      },
    },
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(formData, name, value);
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleSelectBatch = (e, _, r) => {
    setSelectValue(r);
  };

  const handleAddBatch = () => {
    if (selectValue) {
      if (state.haveApplied.find((p) => p.value === selectValue.value) || state.notApplied.find((p) => p.value === selectValue.value)) {
        return Message.warning({ content: t`不可重复添加批次` });
      }
      setState({ ...state, notApplied: [...state.notApplied, { ...selectValue, count: 10 }] });
    } else {
      Message.warning({ content: t`请选择批次` });
    }
  };

  const handleDeleteState = (i) => {
    setState((pre) => {
      const arr = { ...pre };
      arr.notApplied.splice(i + (currentPage.notApplied * pageSize.notApplied), 1);
      return arr;
    });
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    const { id: activityId, name: activityName } = formData;
    const toggleData = state.notApplied.map((p) => ({
      couponBatchId: p.value,
      activityId,
      requestedQuantity: p.count,
      activityName,
      couponBatchName: p.label,
    }));
    onSubmit?.(toggleData);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleBatchSubmit = async (result) => {
    try {
      const { count: quantity, id: batchId } = result;
      const { id } = superAddition?.record;
      Dialog.confirm({
        content: t`确定要追加【${id}】吗?`,
        onOk: () => ensureEdit(activity?.id, { quantity, batchId }),
      });
    } catch (error) {
      Message.error({ content: t`追加错误` });
    }
  };

  const ensureEdit = async (id, args) => {
    await store.api.activityApplyAppend(id, args);
    Message.success({ content: t`追加成功` });
    setSuperAddition({});
    await init();
  };

  const onClose = () => {
    setSuperAddition({ visible: false });
  };

  return (
    <Form
      inline
      isPreview={false}
      {...formProps}
      value={formData}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={formData}
        columns={1}
        overrideModel={overrideModel}
        fields={(['batchId'])}
      />
      <Form.Item
        label={t`新增批次`}
        labelAlign="top"
        name="batchList"
      >
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={currentPage.notApplied}
          pageSize={pageSize.notApplied}
          total={state.notApplied.length}
          onFetch={({ page, size }) => {
            setCurrentPage({ ...currentPage, notApplied: page });
            size && setPageSize({ ...pageSize, notApplied: size });
          }}
          dataSource={notCurrentPageData}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.priceIdx(i, currentPage.notApplied, pageSize.notApplied) },
            {
              title: t`名称`,
              dataIndex: 'label',
              width: 200,
            },
            {
              title: t`id`,
              dataIndex: 'value',
              width: 200,
            },
            {
              title: t`数量`,
              dataIndex: 'count',
              width: 200,
              cell: (v, i) => (
                <NumberPicker
                  onChange={(value) => setState((pre) => {
                    const toggle = { ...pre };
                    toggle.notApplied[i].count = value;
                    return toggle;
                  })}
                  value={v}
                />
              ),
            },
            {
              title: t`操作`,
              dataIndex: '',
              cell: (_, i) => <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteState(i, 'notApplied')}>{t`删除`}</Button>,
            },
          ]}
        />
      </Form.Item>
      <Form.Item
        label={t`已申请批次 ( 追加置灰表示批次已禁用 )`}
        labelAlign="top"
        name="batchList"
      >
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={currentPage.haveApplied}
          pageSize={pageSize.haveApplied}
          total={state.haveApplied.length}
          onFetch={({ page, size }) => {
            setCurrentPage({ ...currentPage, haveApplied: page });
            size && setPageSize({ ...pageSize, haveApplied: size });
          }}
          dataSource={haveCurrentPageData}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.priceIdx(i, currentPage.haveApplied, pageSize.haveApplied) },
            {
              title: t`名称`,
              dataIndex: 'label',
              width: 200,
            },
            {
              title: t`id`,
              dataIndex: 'value',
              width: 200,
            },
            {
              title: t`已申领`,
              dataIndex: 'count',
              width: 100,
            },
            {
              title: t`剩余数量`,
              dataIndex: 'mayApply',
              width: 100,
              cell: (v) => <span style={{ color: v == 0 && 'red' }}>{v}</span>,
            },
            {
              title: t`操作`,
              dataIndex: '',
              cell: (_, i, record) => <Button type="primary" text disabled={!record?.enable} onClick={() => setSuperAddition({ visible: 'open', onClose, record })}>{t`追加`}</Button>,
            },
          ]}
        />
      </Form.Item>
      <DrawerFooter>
        <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>
        <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
      </DrawerFooter>
      <SuperAddition modal={superAddition} onSubmit={handleBatchSubmit} />
    </Form>
  );
};

export default observer(RelevancyActivity);
